<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Laravel\Scout\Searchable;

class Post extends Model
{
    use Searchable;

    protected $guarded;
    protected $fillable = ['title', 'content', 'user_id'];

    //定义索引里面的 type
    public function searchableAs()
    {
        return 'post';
    }

    //定义有哪些字段需要搜索
    public function toSearchableArray()
    {
        return [
            'title'     => $this->title,
            'content'   => $this->content
        ];
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function comments()
    {
        return $this->hasMany('App\Comment')->orderBy('created_at', 'desc');
    }

    //文章和赞的关联(每个用户每篇文章只能有 一个赞)
    public function zan($user_id)
    {
        return $this->hasOne(Zan::class)->where('user_id', $user_id);
    }

    //文章有多个赞
    public function zans()
    {
        return $this->hasMany(Zan::class);
    }
    
    //获取属于某个用户的文章
    public function scopeAuthBy(Builder $query, $user_id){
        return $query->where('user_id', $user_id);
    }

    //文章和标题的关联
    public function postTopics()
    {
        return $this->hasMany(\App\postTopic::class, 'post_id', 'id');
    }

    //查找不在某个 topic 中的文章
    public function scopeTopicNotBy(Builder $query, $topic_id){
        return $query->doesntHave('postTopics', 'and', function($q) use($topic_id) {
            $q->where('topic_id', $topic_id);
        });
    }

    public static function boot()
    {
        parent::boot();

        static::addGlobalScope('available', function (Builder $builder) {
            $builder->whereIn('status', [0, 1]);
        });
    }
}
